package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.FriendHXEntity;

public class HXFriendDAO {
//	CREATE TABLE friend_hx (
//			  id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
//			  username VARCHAR(200) NOT NULL,
//			  friend_name VARCHAR(200) NOT NULL,
//			  status INT NOT NULL
//			) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci;

	public void add(Connection conn, String username, List<String> friendList) throws SQLException {
		PreparedStatement ps = conn
				.prepareStatement("insert into friend_hx (username,friend_name,status) values(?,?,?)");
		for (String friend : friendList) {
			ps.setString(1, username);
			ps.setString(2, friend);
			ps.setInt(3, 1);
			ps.addBatch();
		}
		ps.executeBatch();
	}

	public List<FriendHXEntity> list(Connection conn) throws SQLException {
		List<FriendHXEntity> list = new LinkedList<>();
		PreparedStatement ps = conn.prepareStatement("select * from friend_hx where status=1");
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			FriendHXEntity entity = fill(rs);
			list.add(entity);
		}
		return list;
	}

	private FriendHXEntity fill(ResultSet rs) throws SQLException {
		FriendHXEntity entity = new FriendHXEntity();
		entity.setFriend_name(rs.getString("friend_name"));
		entity.setId(rs.getInt("id"));
		entity.setStatus(rs.getInt("status"));
		entity.setUsername(rs.getString("username"));
		return entity;
	}

	public void update(Connection connection, FriendHXEntity entity) throws SQLException {
		PreparedStatement ps = connection
				.prepareStatement("update friend_hx set username=?,friend_name=?,status=? where id =?");
		ps.setString(1, entity.getUsername());
		ps.setString(2, entity.getFriend_name());
		ps.setInt(3, entity.getStatus());
		ps.setInt(4, entity.getId());
		ps.executeUpdate();
	}

	public int countFriend(Connection connection, String username) throws SQLException {
		PreparedStatement ps = connection.prepareStatement("select count(*) from friend_hx where username like ?");
		ps.setString(1, username);
		ResultSet rs = ps.executeQuery();
		int count=0;
		if (rs.next()) {
			count=rs.getInt(1);
		}
		return count;
	}
}
